package com.hitqz.robot.biz.flow.component.agv;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotMapPos;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.hitqz.robot.biz.service.RobotMapPosService;
import com.hitqz.robot.biz.service.RobotService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author xupkun
 * @date 2025/4/2
 */

@Slf4j
@LiteflowComponent(value = "AgvPutWheel", name = "[轮对/轮轴]暂存线存放完成")
@RequiredArgsConstructor
public class AgvPutWheel extends NodeComponent {

    private final RobotService robotService;

    private final RobotMapPosService robotMapPosService;

    private final RestTemplate restTemplate;

    @Override
    public void process() throws Exception {
        LiteFlowUtil.checkInterruptFlag();
        try {
            FlowContextDto dto =  this.getRequestData();
            FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                    .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
            Robot robot = robotService.getDefaultRobot();
            String pjData = String.valueOf(ticketsDto.getModalData().get("pjData"));

            String targetPosName = Optional.ofNullable(ticketsDto.getModalData().get("targetPosName"))
                    .orElse(ticketsDto.getModalData().get("targetPosCode")).toString();

            RobotMapPos targetPos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                    .eq(RobotMapPos::getName, targetPosName)
                    .eq(RobotMapPos::getMapCode, robot.getMapCode()));
            if (targetPos == null) {
                targetPos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                        .eq(RobotMapPos::getCode, targetPosName)
                        .eq(RobotMapPos::getMapCode, robot.getMapCode()));
            }
            //下一个点
            List<RobotMapPos> preTargetPosList = robotMapPosService.list(Wrappers.<RobotMapPos>lambdaQuery()
                    .like(RobotMapPos::getPreCode, targetPos.getCode())
                    .eq(RobotMapPos::getMapCode, robot.getMapCode()));
            AtomicReference<RobotMapPos> preTargetPos = new AtomicReference<>();
            RobotMapPos finalTargetPos = targetPos;
            preTargetPosList.forEach(t-> {
                if (Arrays.stream(t.getPreCode().split(",")).anyMatch(s-> s.equals(finalTargetPos.getCode()))) {
                    preTargetPos.set(t);
                }
            });
            String putAgvStatus = "http://192.10.13.20:9999/lzms/agvPut?status=1&sbbh=5401&sbbh_wz=01N03";
            if (StrUtil.isNotBlank(pjData)) {
                try {
                    JSONObject jsonObject = JSON.parseObject(pjData);
                    // 循环获取 JSON 的 key
                    for (String key : jsonObject.keySet()) {
                        putAgvStatus = putAgvStatus + "&" + key + "=" + jsonObject.getString(key);
                    }
                } catch (Exception e) {
                    log.error("解析 JSON 数据时发生异常: {}", e.getMessage(), e);
                }
            }
            putAgvStatus = putAgvStatus.replace("5401",
                    robot.getRobotName()).replace("01N03", targetPos.getName() + "," + preTargetPos.get().getName());
            // 发送请求
            log.info("放下的请求是: {}", putAgvStatus);
            String putResult = restTemplate.postForObject(
                    putAgvStatus, ""
                    , String.class);
            log.info("请求放料的结果:" + putResult);
        } catch (Exception e) {
            log.info("请求异常:" + e.getMessage());
        }





    }



    private String sendDispatch(String requestBody, String uri) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>( requestBody, headers);
            log.info("请求地址{} 参数: {}", uri
                    , requestBody);
            String response = restTemplate.postForObject(uri, requestEntity, String.class);
            log.info("任务返回接果: " + response);
            return response;
        } catch (Exception e) {
            log.info("请求地址发生异常:" + e.getMessage());
        }
        return null;
    }
}
